package com.cory.utils.file;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 使用了google zxing作为二维码生成工具
 */
@Slf4j
public class ZxingUtils {
    
    public static final int BLACK = 0xFF000000;
    public static final int WHITE = 0xFFFFFFFF;

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    /** 将内容contents生成宽高均为width的图片，图片路径由imgPath指定
     */
    public static File getQRCodeImge(String contents, int width, String imgPath) {
        return getQRCodeImge(contents, width, width, imgPath);
    }

    /** 将内容contents生成宽为width，高为height的图片，图片路径由imgPath指定
     */
	public static File getQRCodeImge(String contents, int width, int height, String imgPath) {
		try {
            Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF8");

			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

            File imageFile = new File(imgPath);
			writeToFile(bitMatrix, "png", imageFile);

            return imageFile;

		} catch (Exception e) {
			log.error("create QR code error!", e);
            return null;
		}
	}
	
	/** 将内容contents生成宽为width，高为height的图片，并返回数据流
     */
	public static InputStream getQRCodeInputStream(String contents, int width, int height) {
        try {
        	Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
            
            BitMatrix bitMatrix = (new MultiFormatWriter()).encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

            BufferedImage image = new BufferedImage(width, height, 1);
            for(int x = 0; x < width; ++x) {
                for(int y = 0; y < height; ++y) {
                    image.setRGB(x, y, bitMatrix.get(x, y)?-16777216:-1);
                }
            }

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(image, "png", imOut);
            InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
            return inputStream;
        } catch (Exception e) {
            log.error("create QR code error!", e);
            return null;
        }
    }
	
	/** 将内容contents生成长宽为width，高为height的Base64图片，可直接用于img src标签上
     */
	public static String getQRCodeImageBase64(String contents, int width, int height){
		InputStream inputStream = getQRCodeInputStream(contents, width, height);
		
		try{
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();

            return "data:image/png;base64," + new String(Base64.encodeBase64(data));
        }catch (Exception e) {
            log.error("create QR code error!", e);
            return null;
        }
	}
	
	/** 二维码解码
     */
	public static String decodeQRCode(String imgPath) {
		BufferedImage image = null;
		Result result = null;
		
		try {
			image = ImageIO.read(new File(imgPath));
			if (image == null) {
				return null;
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

			Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF8");

			result = new MultiFormatReader().decode(bitmap, hints);
			return result.getText();
		} catch (Exception e) {
			log.error("decode QR code error!", e);
			return null;
		}
	}
}
